package com.lx.huimail.fragment;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.google.gson.Gson;
import com.lx.huimail.R;
import com.lx.huimail.activity.p_status_act.WaitGetGoodsActivity;
import com.lx.huimail.adapter.OrderManagerAdapter;
import com.lx.huimail.configs.Config;
import com.lx.huimail.utils.PullToRefreshView;
import com.lx.huimail.utils.PullToRefreshView.OnFooterRefreshListener;
import com.lx.huimail.utils.PullToRefreshView.OnHeaderRefreshListener;
import com.lx.huimail.weight.ActionItem;
import com.lx.huimail.weight.TitlePopup;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;

import okhttp3.Call;

/**
 * A simple {@link Fragment} subclass.
 */
public class OrderFragment extends Fragment implements View.OnClickListener,OnHeaderRefreshListener, OnFooterRefreshListener{
    private PullToRefreshView mPullToRefreshView;
    private TitlePopup titlePopup;
    private TextView iv_show_Pop;
    private EditText etSearch;
    private Button search;
    public static RecyclerView recyclerView;
    public static OrderManagerAdapter orderManagerAdapter;
    public static String custid="";

    private LocationClient mLocClient;
    private String province, city, district;
    private String  latitude, lontitude;
    public static String TAG = "LocTestDemo";
    public static FragmentActivity instance;

    private View view;
    private ViewPager mPaper;
    private FragmentPagerAdapter mAdapter;
    private List<Fragment> mFragments = new ArrayList<Fragment>();
    private TextView all,daipeisong,peisongzhong,wancheng;
    private ViewPager viewpager;
    private View view1,view2,view3,view4;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_order, container, false);
        instance=getActivity();
        mLocClient =new LocationClient(getActivity());
        mLocClient.registerLocationListener( new MyLocationListenner());
        setLocationOption();
        mLocClient.start();
        inint(view);
        SharedPreferences sp=getActivity().getSharedPreferences("user", Context.MODE_PRIVATE);
        custid=sp.getString("custid","-1111");
        mAdapter = new FragmentPagerAdapter(getChildFragmentManager()) {

            @Override
            public int getCount() {
                return mFragments.size();
            }

            @Override
            public Fragment getItem(int arg0) {
                return mFragments.get(arg0);
            }
        };
        mPaper.setAdapter(mAdapter);
        mPaper.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            private int currentIndex;

            @Override
            public void onPageSelected(int position) {
                resetColor();
                switch (position) {
                    case 0:
                        all.setTextColor(getResources().getColor(R.color.blue));
                        view1.setBackgroundColor(getResources().getColor(R.color.blue));
                        break;
                    case 1:
                        daipeisong.setTextColor(getResources().getColor(R.color.blue));
                        view2.setBackgroundColor(getResources().getColor(R.color.blue));
                        break;
                    case 2:
                        peisongzhong.setTextColor(getResources().getColor(R.color.blue));
                        view3.setBackgroundColor(getResources().getColor(R.color.blue));
                        break;
                    case 3:
                        wancheng.setTextColor(getResources().getColor(R.color.blue));
                        view4.setBackgroundColor(getResources().getColor(R.color.blue));
                        break;
                    default:
                        all.setTextColor(getResources().getColor(R.color.blue));
                        view1.setBackgroundColor(getResources().getColor(R.color.blue));
                        break;
                }
                currentIndex = position;
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });
        return view;
    }

    private void inint(View view) {
        all=(TextView)view.findViewById(R.id.all);
        daipeisong=(TextView)view.findViewById(R.id.daipeisong);
        peisongzhong=(TextView)view.findViewById(R.id.peisongzhong);
        wancheng=(TextView)view.findViewById(R.id.wancheng);
        mPaper=(ViewPager)view.findViewById(R.id.viewpager);
        etSearch=(EditText)view.findViewById(R.id.poi_et_search) ;
        search=(Button)view.findViewById(R.id.bt_search) ;
        view1=(View)view.findViewById(R.id.view1);
        view2=(View)view.findViewById(R.id.view2);
        view3=(View)view.findViewById(R.id.view3);
        view4=(View)view.findViewById(R.id.view4);
        all.setTextColor(getResources().getColor(R.color.blue));
        view1.setBackgroundColor(getResources().getColor(R.color.blue));
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(etSearch.length()==0){
                    Toast.makeText(getContext(),"请输入订单号",Toast.LENGTH_SHORT).show();
                }else {
                    Intent intent=new Intent();
                    intent.putExtra("orderno",etSearch.getText()+"");
                    intent.putExtra("status","12321343");
                    intent.setClass(getContext(), WaitGetGoodsActivity.class);
                    startActivity(intent);
                }

            }
        });
        all.setOnClickListener(this);
        daipeisong.setOnClickListener(this);
        peisongzhong.setOnClickListener(this);
        wancheng.setOnClickListener(this);

        Page1 f1 = new Page1();
        Page2 f2 = new Page2();
        Page3 f3 = new Page3();
        Page4 f4 = new Page4();

        mFragments.add(f1);
        mFragments.add(f2);
        mFragments.add(f3);
        mFragments.add(f4);

    }
    public void resetColor(){
        all.setTextColor(Color.rgb(56,56,56));
        daipeisong.setTextColor(Color.rgb(56,56,56));
        peisongzhong.setTextColor(Color.rgb(56,56,56));
        wancheng.setTextColor(Color.rgb(56,56,56));
        view1.setBackgroundColor(getResources().getColor(R.color.white));
        view2.setBackgroundColor(getResources().getColor(R.color.white));
        view3.setBackgroundColor(getResources().getColor(R.color.white));
        view4.setBackgroundColor(getResources().getColor(R.color.white));
    }
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.all:
                resetColor();
                all.setTextColor(getResources().getColor(R.color.blue));
                view1.setBackgroundColor(getResources().getColor(R.color.blue));
                mPaper.setCurrentItem(0);
                break;
            case R.id.daipeisong:
                resetColor();
                daipeisong.setTextColor(getResources().getColor(R.color.blue));
                view2.setBackgroundColor(getResources().getColor(R.color.blue));
                mPaper.setCurrentItem(1);
                break;
            case R.id.peisongzhong:
                resetColor();
                peisongzhong.setTextColor(getResources().getColor(R.color.blue));
                view3.setBackgroundColor(getResources().getColor(R.color.blue));
                mPaper.setCurrentItem(2);
                break;
            case R.id.wancheng:
                resetColor();
                wancheng.setTextColor(getResources().getColor(R.color.blue));
                view4.setBackgroundColor(getResources().getColor(R.color.blue));
                mPaper.setCurrentItem(3);
                break;

            default:
                break;
        }
    }
    /**
     * ViewPager适配器
     */
    public class MyPagerAdapter extends PagerAdapter {
        public List<Activity> mListViews;

        public MyPagerAdapter(List<Activity> mListViews) {
            this.mListViews = mListViews;
        }


        @Override
        public void finishUpdate(View arg0) {
        }

        @Override
        public int getCount() {
            return mListViews.size();
        }



        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == (arg1);
        }

        @Override
        public void restoreState(Parcelable arg0, ClassLoader arg1) {
        }

        @Override
        public Parcelable saveState() {
            return null;
        }

        @Override
        public void startUpdate(View arg0) {
        }
    }
    //设置相关参数
    private void setLocationOption(){
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);				//设置是否打开gps，使用gps前提是用户硬件打开gps。默认是不打开gps的。
        option.setCoorType("bd09ll");		//设置坐标类型
        option.setServiceName("com.baidu.location.service_v2.9");
        option.setPoiExtraInfo(true);//设置是否需要POI的电话地址等详细信息
        option.setPoiNumber(10);
        option.setAddrType("all");//	设置是否要返回地址信息，默认为无地址信息。String 值为 all时，表示返回地址信息。其他值都表示不返回地址信息。
        option.setScanSpan(3000);	//设置定位模式，小于1秒则一次定位;大于等于1秒则定时定位
        option.setPriority(LocationClientOption.NetWorkFirst);      //设置网络优先,/不设置，默认是gps优先
        option.disableCache(true);
        mLocClient.setLocOption(option);
    }

    /**
     * 监听函数，又新位置的时候，格式化成字符串，输出到屏幕中
     */
    public class MyLocationListenner implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null)
                return;
            StringBuffer sb = new StringBuffer(256);
            latitude=String .valueOf(location.getLatitude());
            lontitude=String.valueOf(location.getLongitude());
            if (location.getLocType() == BDLocation.TypeGpsLocation){
                sb.append("\nspeed : ");
                sb.append(location.getSpeed());
                sb.append("\nsatellite : ");
                sb.append(location.getSatelliteNumber());
            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation){
                province = location.getProvince();
                city = location.getCity();
                district = location.getDistrict();
            }
            logMsg(latitude+lontitude);
        }
        /**
         * 显示字符串
         * @param str
         */
        public void logMsg(String str) {
            try {
                System.out.print("经纬度=="+str);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        @Override
        public void onReceivePoi(BDLocation arg0) {
            // TODO Auto-generated method stub

        }

    }
    protected boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }
    /**
     * 检查GPS是否开启
     * @return
     */
    public boolean isGPSEnabled(){
        LocationManager locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }
    /**
     * 打开gps设置界面
     */
    public void openGPSSetting(){
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            this.startActivity(intent);

        }catch(ActivityNotFoundException ex){

            // The Android SDK doc says that the location settings activity
            // may not be found. In that case show the general settings.

            // General settings activity
            intent.setAction(Settings.ACTION_SETTINGS);
            try {
                this.startActivity(intent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    @Override
    public void onDestroy() {
        mLocClient.stop();
        super.onDestroy();
    }
    @Override
    public void onFooterRefresh(PullToRefreshView view) {
        mPullToRefreshView.postDelayed(new Runnable() {

            @Override
            public void run() {
                handler.sendEmptyMessage(1);

                mPullToRefreshView.onFooterRefreshComplete();
            }
        }, 2000);

    }

    @Override
    public void onHeaderRefresh(PullToRefreshView view) {
        mPullToRefreshView.postDelayed(new Runnable() {

            @Override
            public void run() {
                handler.sendEmptyMessage(1);
                mPullToRefreshView.onHeaderRefreshComplete();
            }
        }, 2000);


    }
	/*-----------刷新接口方法实现-------	*/

    Handler handler = new Handler() {
        public void handleMessage(Message message) {
            super.handleMessage(message);
            mPullToRefreshView.onFooterRefreshComplete();

        }
    };
}
